package cn.tonyandmoney.voicenotes.wav.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import cn.tonyandmoney.voicenotes.R
import cn.tonyandmoney.voicenotes.greendao.utils.GreenDaoHelper
import cn.tonyandmoney.voicenotes.notes.config.Constants
import cn.tonyandmoney.voicenotes.notes.entity.NoteRecord
import cn.tonyandmoney.voicenotes.notes.entity.TRecord
import cn.tonyandmoney.voicenotes.utils.DateUtils
import cn.tonyandmoney.voicenotes.wav.utils.AudioEditUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.zlzsy.app.base.ui.BaseActivity
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * 音频文件的拼接
 */
class AudioJointActivity : BaseActivity() {

    private val files = mutableListOf<TRecord>()
    private val recordDao = GreenDaoHelper.session().tRecordDao

    private var mNoteId: Long = 0
    private lateinit var mRecord: TRecord

    @SuppressLint("SetTextI18n")
    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        val id = intent.getLongExtra("id", -1L)
        mNoteId = intent.getLongExtra("noteId", 0)
        if (id < 1) {
            longToast("系统错误。")
            finish()
            return
        }
        mRecord = recordDao.load(id)
        files.add(mRecord)
        verticalLayout {
            padding = dip(10)
            linearLayout {
                orientation = LinearLayout.HORIZONTAL
                gravity = Gravity.CENTER_VERTICAL
                val textView = textView {
                    minHeight = dip(45)
                    padding = dip(10)
                    hint = "请选择音频"
                    text = mRecord.content + "\n" + mRecord.fileName
                }.lparams(0, wrapContent, 1f)
                textView {
                    text = context.getString(R.string.select)
                    gravity = Gravity.CENTER
                    backgroundResource = R.drawable.bg_btn_ripper
                    onClick { selectFile(textView, 0) }
                    leftPadding = dip(5)
                    rightPadding = leftPadding
                }.lparams(wrapContent, dip(35))
            }

            linearLayout {
                orientation = LinearLayout.HORIZONTAL
                gravity = Gravity.CENTER_VERTICAL
                val textView = textView {
                    minHeight = dip(45)
                    padding = dip(10)
                    hint = "请选择音频"
                }.lparams(0, wrapContent, 1f)
                textView {
                    text = context.getString(R.string.select)
                    gravity = Gravity.CENTER
                    backgroundResource = R.drawable.bg_btn_ripper
                    leftPadding = dip(5)
                    rightPadding = leftPadding
                    onClick { selectFile(textView, 1) }
                }.lparams(wrapContent, dip(35))
            }

            textView {
                backgroundResource = R.drawable.btn_round_corner
                setText(R.string.action_save)
                gravity = Gravity.CENTER
                textSize = 18f
                textColor = resources.getColor(R.color.white)
                onClick { save() }
            }.lparams(matchParent, dip(45)) {
                topMargin = dip(20)
            }

        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun selectFile(textView: TextView, index: Int) {
        val list = recordDao.loadAll()
        val items = list.map {
            it.content + "\n" + it.fileName
        }
        MaterialDialog.Builder(this)
                .title("选择文件")
                .items(items)
                .itemsCallbackSingleChoice(-1, { _, _, position, text ->
                    val record = list[position]
                    textView.text = text
                    if (index < files.size)
                        files.removeAt(index)
                    files.add(index, record)
                    return@itemsCallbackSingleChoice true
                })
                .positiveText("确定")
                .negativeText("取消")
                .show()
    }

    private fun save() {
        if (files.size != 2) {
            longToast("请先选择文件")
            return
        }
        showLoadingDialog("正在合成...")
        Single.create<TRecord> {
            val outPath = Constants.sJonitPath + DateUtils.toYYYYMMDDHHmmss() + "/" + files[0].fileName
            AudioEditUtil.jointAudioWithSame(files[0], files[1], outPath)
            val record = TRecord()
            record.content = mRecord.content + "_副本" + DateUtils.toDDHHMM()
            record.path = outPath
            record.duration = files[0].duration + files[1].duration
            record.id = recordDao.insert(record)
            GreenDaoHelper.session()
                    .noteRecordDao
                    .insert(NoteRecord(mNoteId,record.id))
            it.onSuccess(record)
        }.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    hideLoadingDialog()
                    MaterialDialog.Builder(this)
                            .title("提示")
                            .content("合成音频成功，已保存到文件：\n$it")
                            .positiveText("确定")
                            .show()
                }, {
                    hideLoadingDialog()
                    MaterialDialog.Builder(this)
                            .title("错误")
                            .content("合成音频错误，请重试。")
                            .positiveText("确定")
                            .show()
                })


    }
}